package com.yonyou.train.util.index;

import com.yonyou.train.exception.ReleaseCourseException;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class SearcherUtil {
    //索引目录地址
    public  static String indexFolder = null;
    public static IndexReader indexReader = null;
    public static   IndexSearcher indexSearcher =null;
    static {
        Properties properties = new Properties();
        try {
            indexFolder = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"indexfolder";
            //指定目录
            File folder = new File(indexFolder);
            Directory directory = null;


            directory = FSDirectory.open(folder);
            //indexreader
             indexReader = DirectoryReader.open(directory);
            //定义indexSearcher
            //indexreader打开需要耗费很大的系统资源，建议使用一个indexreader，如果索引进行添加、修改或删除需要打开新的Reader才可以搜索到
             indexSearcher = new IndexSearcher(indexReader);
        } catch (IOException e) {
            throw new ReleaseCourseException("找不到索引目录配置文件");
        }
    }
    public static List<String> getNames(String search){
        //创建查询对象，根据文件名称域搜索匹配文件名称的文档
        Query query = new TermQuery(new Term("pinyin", search));
        List<String> names = new ArrayList<String>();
        TopDocs topDocs = null;
        try {
            topDocs = indexSearcher.search(query, 1000);
            //提取搜索结果
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            for (ScoreDoc scoreDoc : scoreDocs) {
                //文档id
                int docID = scoreDoc.doc;
                //得到文档
                Document doc = indexSearcher.doc(docID);
                //输出文件内容
                names.add(doc.get("name"));
            }
        } catch (IOException e) {
            throw new ReleaseCourseException("服务器中没有该目录文件");
        }
        return names;
    }
}
